#!/bin/bash
# - rpm_repo

. $LKP_SRC/lib/debug.sh
. $LKP_SRC/lib/upload.sh

[ -n "$rpm_repo" ] || die "rpm_repo is empty"
benchmark=${rpm_repo##*/}
sync_dest="/initrd/rpmbuild-pkg/${os_mount}/${os}/${os_arch}/${os_version}/${benchmark}"

init_workspace()
{
	# generate workspace in ${HOME}
	rpmdev-setuptree
}

get_pkgfile()
{
	curl -sS -H 'Content-Type: Application/json' -XPOST "$LKP_SERVER"':8100/git_command' \
	-d '{"git_repo": "'${rpm_repo}'", "git_command": ["git-show", "HEAD:'$1'"]}' -o "${2}"
}

download_rpm_repo()
{
	filelist=$(curl -sS -H 'Content-Type: Application/json' -XPOST "$LKP_SERVER"':8100/git_command' \
		-d '{"git_repo": "'${rpm_repo}'", "git_command": ["git-ls-files", "."]}')
	for pkgfile in ${filelist[*]}
	do
		local dir="SOURCES"
		echo $pkgfile | egrep "\.spec$" && dir="SPECS"
		get_pkgfile "$pkgfile" "${HOME}/rpmbuild/${dir}/$pkgfile"
	done
}

build_rpm()
{
	spec_dir=${HOME}/rpmbuild/SPECS/$benchmark.spec
	sed -i 's/^\(Source[^ ]*:[ \t]*\)https/\1http/g' `grep http -rl $benchmark.spec`
	# Install build depends
	yum-builddep -y $spec_dir
	# Download tar.gz to default path ${HOME}/rpmbuild/SOURCE
	spectool -g -R $spec_dir
	# Building rpm or srpm packages
	rpmbuild -ba $spec_dir
}

upload_rpm_pkg()
{
	# rpm package will be generated in "${HOME}/rpmbuild/SRPMS" and "${HOME}/rpmbuild/RPMS"
	for file in $(find ${HOME}/rpmbuild/ -type f -name "*.rpm")
	do
		upload_one_curl ${file} ${sync_dest}
	done
}

init_workspace
download_rpm_repo
build_rpm
upload_rpm_pkg
